package com.fdhwws.web.service.impl;

import com.fdhwws.web.dao.UserDao;
import com.fdhwws.web.dao.impl.UserDaoImpl;
import com.fdhwws.web.domain.User;
import com.fdhwws.web.entity.AjaxResult;
import com.fdhwws.web.service.UserService;
import com.fdhwws.web.util.InfoSecurityUtil;
import com.mysql.cj.util.StringUtils;

import java.util.List;

public class UserServiceImpl implements UserService {

    private final UserDao userDao = new UserDaoImpl();

    @Override
    public User getUserById(Integer id) {
        if (id == null) return null;
        return userDao.selectById(id);
    }

    @Override
    public User login(String username, String password) {
        if (StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(password)) {
            return null;
        }
        return userDao.selectByUsernameAndPassword(username, InfoSecurityUtil.encrypt(password));
    }

    @Override
    public AjaxResult register(User user) {
        if (StringUtils.isNullOrEmpty(user.getUsername()) || StringUtils.isNullOrEmpty(user.getPassword())) {
            return AjaxResult.error("用户名或密码不能为空", null);
        }
        if (user.getPassword().length() < 6 || user.getPassword().length() > 20) {
            return AjaxResult.error("密码长度必须在6到20个字符之间", null);
        }
        if (user.getUsername().length() > 20) {
            return AjaxResult.error("用户名长度不能超过20个字符", null);
        }
        User userSearch = userDao.selectByUsername(user.getUsername());
        if (userSearch != null) {
            return AjaxResult.error("用户名已存在", null);
        }
        user.setPassword(InfoSecurityUtil.encrypt(user.getPassword()));
        return AjaxResult.success("注册成功", userDao.insert(user));
    }


    @Override
    public AjaxResult getAllUser() {
        List<User> users = userDao.selectAll();
        return AjaxResult.success("获取成功", users);
    }

    @Override
    public AjaxResult updateUser(User user) {
        if (user.getId() == null) {
            return AjaxResult.error("用户id不能为空", null);
        } else {
            userDao.update(user);
            return AjaxResult.success("更新成功", null);
        }
    }
}
